import axios from 'axios'
import { Toast } from 'vant'
import type { LoginCredentials, LoginResponse, UserInfo } from '@/types/auth'

// 创建 axios 实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器 - 添加认证 token
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器 - 统一错误处理
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const message = error.response?.data?.message || '网络错误，请稍后重试'
    Toast(message)
    return Promise.reject(new Error(message))
  },
)



/**
 * 登录API
 *
 * @param data {LoginData}
 * @returns
 */
// export function loginAPI(data: LoginData): AxiosPromise<LoginResult> {
//   const formData = new FormData();
//   formData.append("username", data.username);
//   formData.append("password", data.password);
//   formData.append("captchaKey", data.captchaKey || "");
//   formData.append("captchaCode", data.captchaCode || "");
//   return request({
//     url: "/api/v1/auth/login",
//     method: "post",
//     data: formData,
//     headers: {
//       "Content-Type": "multipart/form-data",
//     },
//   });
// }

// /**
//  * 密码登录
//  * @param credentials 登录凭证
//  */
export const loginAPI = async (credentials: LoginCredentials): Promise<LoginResponse> => {
  console.log('qqq', credentials)
  const response = await api.post<LoginResponse>('/user/login', credentials)
  console.log('ddddd', response)
  return response.data
}

/**
 * 短信验证码登录
 * @param credentials 登录凭证
 */
export const smsLoginAPI = async (credentials: {
  phone: string
  smsCode: string
}): Promise<LoginResponse> => {
  const response = await api.post<LoginResponse>('/user/login/sms', credentials)
  return response.data
}

/**
 * 发送短信验证码
 * @param phone 手机号
 */
// 发送短信验证码
export const sendSmsCode = async () => {
// export const sendSmsCode = async (phone: string, type: 'login' | 'register' | 'reset') => {
  try {
    // 模拟发送短信验证码API
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 实际项目中应调用发送短信API
    // await sendSmsCodeAPI(phone, type)

    return true
  } catch (error) {
    console.error('sendSmsCode:', error)
    throw new Error('发送验证码失败，请稍后重试')
  }
}

/**
 * 获取用户信息
 */
export const getUserInfoAPI = async (): Promise<UserInfo> => {
  const response = await api.get<UserInfo>('/user/info')
  return response.data
}

/**
 * 用户注册
 * @param formData 注册表单数据
 */
export const registerAPI = async (formData: FormData): Promise<{ token: string }> => {
  const response = await api.post('/user/register', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
  return response.data
}
